#include <stdio.h>
#include <errno.h>

#define IMG_WIDTH	400
#define IMG_HEIGHT	400
#define RE_MIN	(-1.5 * SCALE)
#define RE_MAX	(1.2 * SCALE)
#define IM_MIN	0
#define IM_MAX	(1.5 * SCALE)
#define SCALE	1000

extern unsigned char iterations(int re, int im, int s);

int main(int argc, char* ragv[])
{
	FILE *fp=fopen("mandelbrot.pgm", "w");
	int i, j;

	if (fp == NULL) {
		fprintf(stderr, "Error opening output file with errno=%d\n", errno);
		return 1;
	}

	/* Write header of output file */
	fprintf(fp, "P2\n");
	fprintf(fp, "#Mandelbrot set\n");
	fprintf(fp, "%d %d\n", IMG_WIDTH, IMG_HEIGHT);
	fprintf(fp, "255\n");

	/* Generate pixels */
	for (i=IMG_HEIGHT-1; i>=0; i--) {
		for (j=0; j<IMG_WIDTH; j++){
			int re = j*(RE_MAX - RE_MIN)/(IMG_WIDTH-1) + RE_MIN;
			int im = i*(IM_MAX - IM_MIN)/(IMG_HEIGHT-1) + IM_MIN;
			fprintf(fp, "%d  ", iterations(re, im, SCALE));
		}
		fprintf(fp, "\n");
	}

	fclose(fp);
	return 0;
}
